package com.fuda.uifinder


import io.zenoh.Session
import io.zenoh.keyexpr.KeyExpr
import io.zenoh.sample.Sample
import org.junit.jupiter.api.Test
import java.time.LocalDateTime
import java.util.Optional
import java.util.concurrent.BlockingQueue
import kotlinx.coroutines.*
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import java.util.concurrent.*

class ZSubTest {


    @Test
    fun testSubscribe() {
        val latch = CountDownLatch(1)
        println("Press CTRL-C to quit...")

        CoroutineScope(Dispatchers.IO).launch {
            Session.open().use { session->
                KeyExpr.tryFrom(ZenohManager.ZENOH_RESPONSE_TOPIC).use { keyExpr ->
                    println("Declaring Subscriber on '$keyExpr'...")
                    session.declareSubscriber(keyExpr).res().use { subscriber ->
                        val receiver: BlockingQueue<Optional<Sample>> =
                            checkNotNull(subscriber.receiver)
                        while (true) {
                            val now = LocalDateTime.now()
                            val wrapper = receiver.take()
                            val sample = wrapper.get()
                            println(">> $now [Subscriber] Received ${sample.kind} ('${sample.keyExpr}': '${sample.value}')")
                        }
                    }
                }
            }
        }

        CoroutineScope(Dispatchers.IO).launch {
            Session.open().use { session->
                KeyExpr.tryFrom(ZenohManager.ZENOH_HEARTBEAT_TOPIC).use { keyExpr ->
                    println("Declaring Subscriber on '$keyExpr'...")
                    session.declareSubscriber(keyExpr).res().use { subscriber ->
                        val receiver: BlockingQueue<Optional<Sample>> =
                            checkNotNull(subscriber.receiver)
                        while (true) {
                            val now = LocalDateTime.now()
                            val wrapper = receiver.take()
                            val sample = wrapper.get()
                            println(">> $now [Subscriber] Received ${sample.kind} ('${sample.keyExpr}': '${sample.value}')")
                        }
                    }
                }
            }
        }

        // Wait until the test is interrupted
        latch.await()
    }

    companion object {

        @JvmStatic
        @AfterAll
        fun tearDown(): Unit {
        }

        @JvmStatic
        @BeforeAll
        fun setUp(): Unit {
            println("Current DYLD_LIBRARY_PATH: ${System.getenv("DYLD_LIBRARY_PATH")}")
        }
    }
}